package cn.sunxyz.idea.cglib;

import net.sf.cglib.proxy.*;
import org.junit.Test;

import java.lang.reflect.Method;

/**
 * Created by yangrd on 2017/5/25.
 */
public class CglibDemo {

    static class MethodInterceptorImpl implements MethodInterceptor {

        @Override
        public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
            System.out.println("before");
            Object result = proxy.invokeSuper(obj, args);
            System.out.println("after");
            return result;
        }
    }

    @Test
    public void testEnhancer() {

        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(UserService.class);
        enhancer.setCallback(new MethodInterceptorImpl());

        UserService demo = (UserService) enhancer.create();
        demo.add("lisi");
    }

    static class CallbackFilterImpl implements CallbackFilter {

        @Override
        public int accept(Method method) {
            System.out.println(method.getName());
            if (method.getName().equals("method"))
                return 1;
            else
                return 1;
        }

    }

    @Test
    public void testCallbackFilter(){
        Callback[] callbacks = new Callback[] {
                new MethodInterceptorImpl(), NoOp.INSTANCE
        };

        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(UserService.class);
        enhancer.setCallbacks(callbacks);
//        allbackFilter可以实现不同的方法使用不同的回调方法
//        CallbackFilter中的accept方法, 根据不同的method返回不同的值i, 这个值是在callbacks中的顺序, 就是调用了callbacks[i]
        enhancer.setCallbackFilter(new CallbackFilterImpl());

        UserService demo = (UserService) enhancer.create();
        demo.add("lisi");
    }
}
